package com.apes.fn.fico.expense;

import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.ApesConst;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.finance.model.IncomeType;
import com.apes.scm.masterdata.party.model.PartyRole;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = ExpenseItemDetails.CONST_TABLE_NAME)
public class ExpenseItemDetails extends BaseModel {
    public static final String CONST_TABLE_NAME = "fn_expense_item_details";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "费用单明细细项序号")
    @Comment("序号")
    private String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "expense_item_id", referencedColumnName = "id")
    @Comment("平台费用明细号")
    private ExpenseItem expenseItem;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    @Comment("公司编码")
    private PartyRole company;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "income_type", referencedColumnName = "id")
    @Comment("费用类型")
    private IncomeType incomeType;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "expense_details_type", referencedColumnName = "id")
    @Comment("费用细项")
    private Enumeration expenseDetailsType;

    @Column(name = "payment_amount", nullable = false, columnDefinition = ApesConst.FIELD_16_4_0)
    @Comment("款项金额")
    private double paymentAmount = 0;

    @Column(name = "expense_amount", nullable = false, columnDefinition = ApesConst.FIELD_16_4_0)
    @Comment("费用金额")
    private double expenseAmount = 0;

    @OneToMany(mappedBy = "expenseItemDetails", cascade = CascadeType.ALL)
    private List<ExpenseItemDetailsBill> expenseItemDetailsBillList = new ArrayList();

    public List<ExpenseItemDetailsBill> getExpenseItemDetailsBillList() {
        if(expenseItemDetailsBillList == null || expenseItemDetailsBillList.isEmpty()) return new ArrayList<>();
        for (ExpenseItemDetailsBill expenseItemDetailsBill : expenseItemDetailsBillList) {
            expenseItemDetailsBill.setExpenseItemDetails(this);
        }
        return expenseItemDetailsBillList;
    }
}
